package org.mango.action;

import com.alibaba.fastjson.JSONObject;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import org.mango.base.BaseAction;
import org.mango.bean.User;
import org.mango.config.QQProperties;
import org.mango.id.Tools;
import org.mango.service.SortService;
import org.mango.service.UserService;
import org.mango.util.KeyUtil;
import org.mango.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by meigang on 17/10/28.
 */
@Controller
@RequestMapping("/")
public class MainAction extends BaseAction {
    @Autowired
    private SortService sortService;
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.getRequestDispatcher("/show/admin/Login.jsx").forward(req,res);
    }

    @RequestMapping("/qq/login")
    public void qqLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/qq/callback")
    public void qqCallback(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
        AccessToken accessTokenObj = null;
        try {
            accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken = null;
            String openID = null;
            long tokenExpireIn = 0L;
            if (accessTokenObj.getAccessToken().equals("")) {
                //我们的网站被CSRF攻击了或者用户取消了授权
                //做一些数据统计工作
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();

                request.getSession().setAttribute("demo_access_token", accessToken);
                request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();

                UserInfo userInfo = new UserInfo(accessToken, openID);
                UserInfoBean uib = userInfo.getUserInfo();

                User user = new User();
                user.setId(openID);
                user.setName(uib.getNickname());
                user.setPhoto(uib.getAvatar().getAvatarURL50());
                user.setLastLoginTime(new Date());
                userService.saveAndUpdateUser(user);

                request.getSession().setAttribute(KeyUtil.USER_SESSION_KEY, JSONObject.toJSONString(user));
                res.sendRedirect("/main");
            }
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/")
    public void f(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.getRequestDispatcher("/f/index").forward(req,res);
    }

    @RequestMapping("/qrcode")
    public void qrcode(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setAttribute("url",req.getParameter("url"));
        req.getRequestDispatcher("/show/admin/Qrcode.jsx").forward(req,res);
    }

    @RequestMapping("/main")
    public void main(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.getRequestDispatcher("/show/admin/Main.jsx").forward(req,res);
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
        req.getSession().invalidate();
        req.getRequestDispatcher("/f/index").forward(req,res);
    }

    /*@RequestMapping("/doLogin")
    public void doLogin(HttpServletRequest req, HttpServletResponse res,User user) throws IOException {
        JSONObject json = new JSONObject();
        if(user.getName().equals("admin")
                && user.getPwd().equals("admin")){
            req.getSession().setAttribute(KeyUtil.USER_SESSION_KEY,JSONObject.toJSONString(user));
            json.put("state",1);
        }else{
            json.put("state",0);
            json.put("msg","用户名密码不正确");
        }
        this.renderJson(res,json.toJSONString());
    }*/

    @RequestMapping("/numAll")
    public void numAll(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("creator", UserUtil.getSessionUser(req).getId());
        Map<String,Integer> retMap = sortService.numAll(map);
        this.renderJson(res,JSONObject.toJSONString(retMap));
    }
}
